package data

import (
	"fmt"
	"sync"
)

var mapLock sync.Mutex
var idServers = make(map[string]*ServerData)
var typeServers = make(map[string]map[string]*ServerData)

type LocalMemServerData struct{}

func (l *LocalMemServerData) AddNewServer(id, addr, types, protocol string) {
	mapLock.Lock()
	ts, ok := typeServers[types]
	if !ok {
		ts = make(map[string]*ServerData)
	}
	newS := &ServerData{
		ServerAddr:     addr,
		ServerId:       id,
		ServerType:     types,
		ServerProtocol: protocol,
	}
	ts[id] = newS
	typeServers[types] = ts
	idServers[id] = newS
	mapLock.Unlock()
}

func (l *LocalMemServerData) GetServerListByType(serverType string) []*ServerData {
	mapLock.Lock()
	serverMap := typeServers[serverType]
	mapLock.Unlock()
	rsp := make([]*ServerData, len(serverMap))
	idx := 0
	for _, v := range serverMap {
		rsp[idx] = v
		idx++
	}
	return rsp
}

func (l *LocalMemServerData) DeleteServer(id string) {
	mapLock.Lock()
	s := idServers[id]
	if s == nil {
		return
	}
	delete(idServers, id)
	tms := typeServers[s.ServerType]
	delete(tms, id)
	typeServers[s.ServerType] = tms
	mapLock.Unlock()
	fmt.Println("移除id=" + id + "的服务成功")
}

func (l *LocalMemServerData) GetServerListByIds(ids []string) []*ServerData {
	results := make([]*ServerData, 0)
	mapLock.Lock()
	for _, o := range ids {
		s, ok := idServers[o]
		if ok {
			results = append(results, s)
		}
	}
	mapLock.Unlock()
	return results
}
